const fs = require('fs');
const path = require('path');
const vscode = require('vscode');
// 默认的函数描述配置
const defaultFunctionDescriptions = {
    "setFitView": `
\`\`\`typescript
(method) setFitView(overlays: Array): void
\`\`\`
\`overlays\` (Array<Overlay>) 覆盖物
\`immediately\` (Boolean = false) 是否立即过渡
\`avoid\` (Array<Number> = [60,60,60,60]) 四周边距，上、下、左、右
\`maxZoom\` (Number = zooms[1]) 最大 zoom 级别`,

    "setZoom": `
(method) setZoom(level: number): void

Sets the map zoom level.

@param \`level\` — The zoom level to set.

@returns
This method returns nothing.`
};

function activate(context) {
    const hoverProvider = vscode.languages.registerHoverProvider(['javascript', 'typescript', 'html', 'vue'], {
        provideHover(document, position, token) {
            const config = vscode.workspace.getConfiguration();
            const userDescriptions = config.get('functionHover.functionDescriptions') || {};
            const functionDescriptions = { ...defaultFunctionDescriptions, ...userDescriptions };
            const markdownFilePath = config.get('functionHover.markdownFilePath');

            const range = document.getWordRangeAtPosition(position);
            const word = document.getText(range);

            let hoverContent = '';

            // 1. 尝试从外部 Markdown 文件中获取内容
            if (markdownFilePath) {
                try {
                    const absolutePath = path.resolve(markdownFilePath);
                    const fileContent = fs.readFileSync(absolutePath, 'utf-8');
                    const mdDescriptions = parseMarkdownFile(fileContent);

                    if (mdDescriptions[word]) {
                        hoverContent = mdDescriptions[word];
                    }
                } catch (error) {
                    console.error('Failed to read the Markdown file:', error);
                }
            }

            // 2. 如果没有找到外部文件中的内容，回退到 settings.json
            if (!hoverContent && functionDescriptions[word]) {
                hoverContent = functionDescriptions[word];
            }

            if (hoverContent) {
                const hoverMarkdown = new vscode.MarkdownString(hoverContent);
                hoverMarkdown.isTrusted = true;  // 允许 Markdown 中的链接等元素
                return new vscode.Hover(hoverMarkdown, range);
            }

            return null;
        }
    });

    context.subscriptions.push(hoverProvider);
}

function parseMarkdownFile(content) {
    const descriptions = {};
    const regex = /###\s*(\w+)\n+([\s\S]+?)(?=\n###|$)/g;

    let match;
    while ((match = regex.exec(content)) !== null) {
        const functionName = match[1];
        const description = match[2].trim();
        descriptions[functionName] = description;
    }

    return descriptions;
}

exports.activate = activate;
